#include "UdpClient.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <netinet/in.h>
#include<signal.h>
#include <arpa/inet.h>
#include"InetAddr.hpp"
#include "Common.hpp"


struct sockaddr_in server;
int sockfd=-1;

void Quit(int sig)
{
    (void)sig;
    std::string message="QUIT";
    int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
    
}

void *Route(void *args)
{
    while (true)
    {
        char buffer[1024];
        struct sockaddr temp;
        socklen_t len = sizeof(temp);
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, &temp, &len);
        buffer[n] = 0;
        std::cerr << buffer << std::endl;
    }
    return nullptr;
}
int main(int argc, char *argv[])
{

    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " serverport" << std::endl;
        Die(1);
    }
    signal(2,Quit);
    u_int16_t serverport = std::stoi(argv[1]);

    // 创建socket
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(2);
    }
    // 填充server信息
    
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY;

    std::string message="....我来了！";
    int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));

    // 创建子线程
    pthread_t tid;
    pthread_create(&tid, nullptr, Route, nullptr);
    // client done
    while (true)
    {
        std::cout << "Please Enter# ";
        fflush(stdout);
        std::string message;
        std::getline(std::cin, message);

        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
        if (n <= 0)
            continue;
        
    }
    return 0;
}